package com.dts.backproject.controller;


import com.dts.backproject.entity.po.LoginResponse;
import com.dts.backproject.entity.po.Result;
import com.dts.backproject.entity.po.User;
import com.dts.backproject.exception.MyException;
import com.dts.backproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "*")
public class LoginAndRegisterController {

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public Result Login(@RequestBody User user) {
        User u = userService.login(user);
        if (u != null) {
            // 创建登录响应对象，不包含密码
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setId(u.getId());
            loginResponse.setEmail(u.getEmail());
            loginResponse.setToken("mock_token_" + u.getId()); // 模拟token，实际项目中应该生成JWT
            
            return Result.success(loginResponse);
        } else {
            System.out.println("密码错误");
            throw new MyException("账号或密码错误！");
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        try {
            userService.register(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }
}
